package com.business_clean.ui.activity.group;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioGroup;

import com.blankj.utilcode.util.LogUtils;
import com.business_clean.R;
import com.business_clean.app.App;
import com.business_clean.app.base.BaseActivity;
import com.business_clean.app.uitl.ActivityForwardUtil;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.data.mode.address.AddressDetailEntity;
import com.business_clean.data.mode.address.AddressListEntity;
import com.business_clean.data.mode.classes.ClassesListEntity;
import com.business_clean.data.mode.group.GroupMangerListEntity;
import com.business_clean.data.mode.roster.RosterList;
import com.business_clean.databinding.ActivityAddGroupBinding;
import com.business_clean.ui.activity.address.AddressManagerActivity;
import com.business_clean.ui.activity.classes.ClassesMangerActivity;
import com.business_clean.ui.activity.personnel.SelectPersonnelActivity;
import com.business_clean.ui.adapter.BaseStringAdapter;
import com.business_clean.viewmodel.request.GroupViewModel;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.luck.picture.lib.decoration.MyGridSpacingItemDecoration;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AddGroupActivity extends BaseActivity<GroupViewModel, ActivityAddGroupBinding> {

    private BaseStringAdapter mAdapter;
    private BaseStringAdapter mClockInAdapter;

    private String uuid;

    private String addressUUIDs = "";
    private String leaderUUIDs = "";

    private String project_class_uuid;

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {

        if (getIntent() != null && getIntent().getExtras() != null) {
            mDatabind.tabbar.setTitle("编辑小组");
            String uuidExtras = getIntent().getExtras().getString("uuid");
            uuid = uuidExtras;
            mViewModel.requestGroupDetail(uuid);
        }


        mAdapter = new BaseStringAdapter(0);
        mClockInAdapter = new BaseStringAdapter(1);
        mDatabind.recycler.setLayoutManager(new GridLayoutManager(this, 4));
        mDatabind.recycler.addItemDecoration(new MyGridSpacingItemDecoration(4, 20, false));
        mDatabind.recycler.setAdapter(mAdapter);

        mClockInAdapter = new BaseStringAdapter(1);
        mDatabind.recyclerClock.setLayoutManager(new GridLayoutManager(this, 2));
        mDatabind.recyclerClock.addItemDecoration(new MyGridSpacingItemDecoration(4, 20, false));
        mDatabind.recyclerClock.setAdapter(mClockInAdapter);

        List<String> strings = new ArrayList<>();
        strings.add("周一");
        strings.add("周二");
        strings.add("周三");
        strings.add("周四");
        strings.add("周五");
        strings.add("周六");
        strings.add("周日");
        mAdapter.setList(strings);

        List<String> stringsClock = new ArrayList<>();
        stringsClock.add("打卡");
        stringsClock.add("免打卡");
        mClockInAdapter.setList(stringsClock);
    }

    private void fillData(AddressDetailEntity data) {
        if (data != null) {
            uuid = data.getUuid();
            project_class_uuid = data.getProject_class_uuid();
            mDatabind.withName.getInputEdit().setText(data.getGroup_name());
            if (!TextUtils.isEmpty(data.getGroup_name())) {
                mDatabind.withForeman.setTvRightText(data.getGroup_name());
            }
            mDatabind.withClasses.setTvRightText(data.getProject_class_name());

            if ("1".equals(data.getAttendance_method())) {
                mClockInAdapter.updateItem(0);
            } else {
                mClockInAdapter.updateItem(1);
                addressUUIDs = "";
                mDatabind.withAddress.setText("请选择");
                mDatabind.withAddress.setTextColor(ContextCompat.getColor(AddGroupActivity.this, R.color.base_primary_text_hint));
                mDatabind.llAddress.setVisibility(View.GONE);
                mDatabind.tvAddress.setVisibility(View.GONE);
            }

            StringBuilder builder = new StringBuilder();
            StringBuilder builderUUIDs = new StringBuilder();


            for (int i = 0; i < data.getAddress_list().size(); i++) {
                builder.append(data.getAddress_list().get(i).getAddress());
                builderUUIDs.append(data.getAddress_list().get(i).getUuid());
                if (i < data.getAddress_list().size() - 1) {
                    builder.append("\n");
                }
                if (i < data.getAddress_list().size() - 1) {
                    builderUUIDs.append(",");
                }
            }

            addressUUIDs = builderUUIDs.toString();
            mDatabind.withAddress.setText(builder.toString());
            mDatabind.withAddress.setTextColor(ContextCompat.getColor(this, R.color.base_primary_text_title));


            StringBuilder leaderbuilder = new StringBuilder();

            for (int i = 0; i < data.getLeader_list().size(); i++) {
                leaderbuilder.append(data.getLeader_list().get(i).getUser_name());
                if (i < data.getLeader_list().size() - 1) {
                    leaderbuilder.append(",");
                }
            }
            mDatabind.withForeman.setTvRightText(leaderbuilder.toString());

            for (String i : data.getWork_day_list()) {
                if (!TextUtils.isEmpty(i)) {
                    mAdapter.updateItem(Integer.parseInt(i) - 1);
                }
            }
        }
    }

    @Override
    public void initObserver() {
        App.appViewModelInstance.getSelectedClasses().observe(this, new Observer<ClassesListEntity>() {
            @Override
            public void onChanged(ClassesListEntity classesListEntity) {
                project_class_uuid = classesListEntity.getUuid();
                mDatabind.withClasses.setTvRightText(classesListEntity.getClass_name());
            }
        });

        App.appViewModelInstance.getSelectedLimitationAddress().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                addressUUIDs = null;
                mDatabind.withAddress.setText("不限制");
                mDatabind.withAddress.setTextColor(ContextCompat.getColor(AddGroupActivity.this, R.color.base_primary_text_title));
            }
        });

        App.appViewModelInstance.getSelectedAddress().observe(this, new Observer<List<AddressListEntity>>() {
            @Override
            public void onChanged(List<AddressListEntity> data) {
                StringBuilder builder = new StringBuilder();
                StringBuilder builderUUIDs = new StringBuilder();

                for (int i = 0; i < data.size(); i++) {
                    if (data.get(i).isChoice()) {
                        builder.append(data.get(i).getAddress()).append("\n");
                        builderUUIDs.append(data.get(i).getUuid()).append(",");
                    }
                }

                if (builder.length() > 0) {
                    builder.deleteCharAt(builder.lastIndexOf("\n"));
                }

                if (builderUUIDs.length() > 0) {
                    builderUUIDs.deleteCharAt(builderUUIDs.length() - 1);
                }

                addressUUIDs = builderUUIDs.toString();
                mDatabind.withAddress.setText(builder.toString());
                mDatabind.withAddress.setTextColor(ContextCompat.getColor(AddGroupActivity.this, R.color.base_primary_text_title));
            }
        });
        App.appViewModelInstance.getSelectedPersonnel().observe(this, new Observer<List<RosterList>>() {
            @Override
            public void onChanged(List<RosterList> data) {
                StringBuilder builder = new StringBuilder();
                StringBuilder builderUUIDs = new StringBuilder();

                for (int i = 0; i < data.size(); i++) {
                    builder.append(data.get(i).getUser_name()).append(",").append("\n");
                    builderUUIDs.append(data.get(i).getUuid()).append(",");
                }

                if (builder.length() > 0) {
                    builder.deleteCharAt(builder.lastIndexOf(","));
                    builder.deleteCharAt(builder.lastIndexOf("\n"));
                }
                if (builderUUIDs.length() > 0) {
                    builderUUIDs.deleteCharAt(builderUUIDs.length() - 1);
                }

                leaderUUIDs = builderUUIDs.toString();
                if (builder.length() > 0) {
                    mDatabind.withForeman.setTvRightText(builder.toString());
                }
            }
        });
    }

    @Override
    public void onRequestSuccess() {
        mViewModel.getSaveGroup().observe(this, new Observer<Object>() {
            @Override
            public void onChanged(Object o) {
                ToastUtil.show("操作成功");
                App.appViewModelInstance.getRefreshGroupManagerList().setValue(true);
                finish();
            }
        });

        mViewModel.getGetOneGroup().observe(this, new Observer<AddressDetailEntity>() {
            @Override
            public void onChanged(AddressDetailEntity groupMangerListEntity) {
                fillData(groupMangerListEntity);
            }
        });
    }

    @Override
    public void onBindViewClick() {
        //班次选择
        mDatabind.withClasses.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putBoolean("isSelected", true);
                ActivityForwardUtil.startActivity(ClassesMangerActivity.class, bundle);
            }
        });
        //打卡地点选择
        mDatabind.llAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putInt("multiple", 2);
                bundle.putString("uuids", addressUUIDs);
                ActivityForwardUtil.startActivity(AddressManagerActivity.class, bundle);
            }
        });
        //选择人员
        mDatabind.withForeman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putInt("multiple", 2);
                bundle.putInt("role_id", 4);
                bundle.putString("uuids", leaderUUIDs);
                ActivityForwardUtil.startActivity(SelectPersonnelActivity.class, bundle);
            }
        });


        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                mAdapter.updateItem(position);
            }
        });

        mClockInAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                mClockInAdapter.updateItem(position);
                if (position == 0) {
                    mDatabind.llAddress.setVisibility(View.VISIBLE);
                    mDatabind.tvAddress.setVisibility(View.VISIBLE);
                } else {
                    addressUUIDs = "";
                    mDatabind.withAddress.setText("请选择");
                    mDatabind.withAddress.setTextColor(ContextCompat.getColor(AddGroupActivity.this, R.color.base_primary_text_hint));
                    mDatabind.llAddress.setVisibility(View.GONE);
                    mDatabind.tvAddress.setVisibility(View.GONE);
                }
            }
        });

        mDatabind.bottom.butBase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mDatabind.withName.getInputText())) {
                    ToastUtil.show("请输入小组名称");
                    return;
                }
                if (mAdapter.getSelectedIndices().size() == 0) {
                    ToastUtil.show("请选择工作日");
                    return;
                }
                if (TextUtils.isEmpty(mDatabind.withClasses.getTvRight())) {
                    ToastUtil.show("请选择班次");
                    return;
                }
                if (TextUtils.isEmpty(uuid) && TextUtils.isEmpty(mDatabind.withAddress.getText().toString())) {
                    ToastUtil.show("请选择打卡地点");
                    return;
                }
                HashMap<String, String> hashMap = new HashMap<>();
                if (!TextUtils.isEmpty(uuid)) {
                    hashMap.put("uuid", "" + uuid);//小组UUID 编辑时必传
                }
                hashMap.put("project_uuid", "" + App.appViewModelInstance.getUserInfo().getValue().getProject().getUuid());//项目UUID
                hashMap.put("group_name", "" + mDatabind.withName.getInputText());//名称
                if (!TextUtils.isEmpty(project_class_uuid)) {
                    hashMap.put("project_class_uuid", "" + project_class_uuid);//班次UUID
                }
//                hashMap.put("clock_in_type", "1");//打卡方式 1自行打卡 2领班打卡
                if (addressUUIDs != null) {
                    hashMap.put("address_uuid_list", "" + addressUUIDs);//工作地址uuid 多个逗号拼接
                }
                hashMap.put("work_day_list", "" + mAdapter.getCommaSeparated1());//工作日 多个逗号拼接
                if (leaderUUIDs != null) {
                    hashMap.put("group_leader_uuid", "" + leaderUUIDs);//领班UUID  领班打卡时必传
                }
                //打卡方式
                hashMap.put("attendance_method", "" + (mClockInAdapter.getSingleSelect() + 1));
                mViewModel.requestSaveGroup(hashMap);
            }
        });
    }
}